<script setup>
import { ref, watch, onMounted, computed } from "vue";
import { storeToRefs } from "pinia";
import { useCompanyStore } from "@/stores/company.js";
import { useUserStore } from "@/stores/userinfo";
import { addFormulaApi, editFormulaApi, getFormulaApi } from "@/api/formula.js";
import { getMeterInfoApi } from "@/api/meter";
import { symbolList, usageOptions } from "@/constants";

// 定义 emit
const emit = defineEmits(["update-formula"]);

// Props
const props = defineProps({
  formulaOptions: {
    type: Array,
    default: () => [],
  },
});

// 表单 ref & 基础状态
const formRef = ref(null);
const id = ref(null);
const visibleContainer = ref(false);
const loading = ref(false);

// 获取 companyId
const { currentCompany } = storeToRefs(useCompanyStore());

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入公式名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符之间", trigger: "blur" },
  ],
  formula: [{ required: true, message: "请输入公式内容", trigger: "blur" }],
  usage: [{ required: true, message: "请选择使用标识", trigger: "change" }],
};

// API 提交数据
const setParam = ref({
  company_id: currentCompany.value?.id,
  name: "",
  formula: "",
  usage: "",
  id: null,
});

// 可选公式列表
const formulaList = ref([]);

// ---------- 新增：usage -> type 映射 ----------
const usageToType = (usage) => {
  if (usage == null || usage === "") return null;

  // 直接支持数字 1/2/3
  const asNum = Number(usage);
  if ([1, 2, 3].includes(asNum)) return asNum;

  // 兼容中英文关键词
  const s = String(usage).toLowerCase();
  if (s.includes("水") || s.includes("water")) return 1;
  if (s.includes("电") || s.includes("power") || s.includes("electric")) return 2;
  if (s.includes("气") || s.includes("gas")) return 3;

  return null;
};

// ---------- 表计相关 ----------
const currentMeterId = ref(null);
const meterList = ref([]);
const loadingMeters = ref(false);

const filterMeterList = computed(() => meterList.value || []);

// 拉取表计列表：依据 usage 推断 type
async function fetchMeterList() {
  try {
    const type = usageToType(setParam.value.usage);

    // 未选使用标识：清空并不请求
    if (!type) {
      meterList.value = [];
      return;
    }

    loadingMeters.value = true;
    const res = await getMeterInfoApi({
      company_id: useUserStore().userCompany.id,
      type, // 关键：按使用标识映射的 type 拉取
    });

    meterList.value = Array.isArray(res?.data) ? res.data : [];
  } catch (error) {
    console.error("获取表计列表失败:", error);
    ElNotification({
      title: "错误",
      message: "获取表计列表失败",
      type: "error",
    });
    meterList.value = [];
  } finally {
    loadingMeters.value = false;
  }
}

// 监听公司变化：刷新公式列表
watch(
  () => currentCompany.value,
  async (newCompany) => {
    if (newCompany?.id) {
      await loadFormulaList();
      // company 变了，若已选 usage，同步刷新表计
      if (setParam.value.usage) {
        await fetchMeterList();
      }
    }
  },
  { immediate: true }
);

// 监听“使用标识”变化：重置当前表计并重拉
watch(
  () => setParam.value.usage,
  async () => {
    currentMeterId.value = null;
    await fetchMeterList();
  }
);

// 加载公式列表
const loadFormulaList = async () => {
  try {
    loading.value = true;
    const res = await getFormulaApi(currentCompany.value.id);
    if (res.code === 200) {
      formulaList.value = res.data || [];
    } else {
      ElMessage.error(res.message || "获取公式列表失败");
    }
  } catch (error) {
    console.error("加载公式列表出错:", error);
    ElMessage.error("加载公式列表时发生错误");
  } finally {
    loading.value = false;
  }
};

// 打开对话框
const open = (row) => {
  visibleContainer.value = true;

  if (row) {
    setParam.value = {
      company_id: currentCompany.value.id,
      name: row.name || "",
      formula: row.formula || "",
      usage: row.usage || "",
      id: row.id ? Number(row.id) : null,
    };
    id.value = row.id ? Number(row.id) : null;
  } else {
    resetForm();
  }

  // 若已有使用标识，立即拉取对应表计
  fetchMeterList();
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  setParam.value = {
    company_id: currentCompany.value?.id,
    name: "",
    formula: "",
    usage: "",
    id: null,
  };
  id.value = null;
  currentMeterId.value = null;
  meterList.value = [];
};

// 从公式中提取所有表计ID
const extractMeterIds = (formula) => {
  if (!formula) return [];
  const regex = /meter\((\d+),START,END\)/g;
  const meterIds = [];
  let match;
  while ((match = regex.exec(formula)) !== null) {
    const meterId = parseInt(match[1]);
    if (!meterIds.includes(meterId)) {
      meterIds.push(meterId);
    }
  }
  return meterIds;
};

// 格式化 deviceids 字段
const formatDeviceIds = (meterIds) => {
  if (!meterIds || meterIds.length === 0) return "";
  return JSON.stringify({ deviceids: meterIds });
};

// 添加公式
const addFormula = async () => {
  try {
    loading.value = true;
    const { id, ...dataWithoutId } = setParam.value;

    // 提取表计ID并格式化
    const meterIds = extractMeterIds(dataWithoutId.formula);
    const deviceidsString = formatDeviceIds(meterIds);

    const submitData = {
      ...dataWithoutId,
      deviceids: deviceidsString,
    };

    const res = await addFormulaApi(submitData);
    if (res.code === 200) {
      ElMessage.success("添加成功");
      await loadFormulaList();
      visibleContainer.value = false;
      emit("update-formula");
    } else {
      ElMessage.error(res.message || "添加失败");
    }
  } catch (error) {
    console.error("添加公式出错:", error);
    ElMessage.error("添加公式时发生错误");
  } finally {
    loading.value = false;
  }
};

// 编辑公式
const editFormula = async () => {
  try {
    loading.value = true;

    const meterIds = extractMeterIds(setParam.value.formula);
    const deviceidsString = formatDeviceIds(meterIds);

    const submitData = {
      ...setParam.value,
      deviceids: deviceidsString,
    };

    const res = await editFormulaApi(submitData);
    if (res.code === 200) {
      ElMessage.success("修改成功");
      await loadFormulaList();
      visibleContainer.value = false;
      emit("update-formula");
    } else {
      ElMessage.error(res.message || "修改失败");
    }
  } catch (error) {
    console.error("编辑公式出错:", error);
    ElMessage.error("编辑公式时发生错误");
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (id.value) {
        await editFormula();
      } else {
        await addFormula();
      }
      resetForm();
    }
  });
};

// 关闭对话框
const handleClose = () => {
  visibleContainer.value = false;
  resetForm();
};

// 选择已有公式
const handleFormulaSelect = (formula) => {
  setParam.value.formula = formula || "";
};

// 插入符号到公式内容中（普通符号）
const insertSymbol = (symbol) => {
  setParam.value.formula += symbol;
};

// 插入 meter(x,START,END)：需先选使用标识和表计
function insertMeterSymbol(symbol) {
  if (!setParam.value.usage) {
    ElMessage.warning("请先选择使用标识");
    return;
  }
  if (!currentMeterId.value) {
    ElMessage.warning("请先选择表计");
    return;
  }
  setParam.value.formula += symbol.replace("x", currentMeterId.value);
}

// 暴露 open
defineExpose({ open });

// 初始化：等待 usage 选择或 open 触发
onMounted(() => {
  // 不做立即请求
});
</script>

<template>
  <el-drawer v-model="visibleContainer" :title="id ? '编辑公式' : '新增公式'" size="50%" :before-close="handleClose">
    <el-form ref="formRef" :model="setParam" :rules="rules" label-width="100px" label-position="top"
      class="custom-form">
      <el-form-item label="公式名称" prop="name">
        <el-input v-model="setParam.name" placeholder="请输入公式名称" clearable :maxlength="50" show-word-limit />
      </el-form-item>

      <el-form-item label="根据选择已有公式快速添加">
        <el-select placeholder="选择已有公式" @change="handleFormulaSelect" clearable class="w-full">
          <el-option v-for="item in formulaList" :key="item.id" :label="item.name" :value="item.formula" />
        </el-select>
      </el-form-item>

      <el-form-item label="使用标识" prop="usage">
        <el-select v-model="setParam.usage" placeholder="请选择使用标识" clearable>
          <el-option v-for="option in usageOptions" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="公式内容" prop="formula">
        <el-input v-model="setParam.formula" type="textarea" :rows="4" placeholder="请输入公式内容" clearable />

        <div class="formula-help">
          <div class="help-header">
            <span class="text-gray-600">支持基础运算符(+,-,*,/,%,^)及常见数学函数</span>
          </div>

          <div class="symbol-table-container">
            <el-table :data="symbolList" border stripe size="small" style="width: 100%" height="400">
              <el-table-column prop="symbol" label="符号" align="center">
                <template #default="scope">
                  <div v-if="scope.row.symbol !== 'meter(x,START,END)'" class="symbol-cell">
                    <span>{{ scope.row.symbol }}</span>
                    <el-button type="primary" link @click="insertSymbol(scope.row.symbol)">插入</el-button>
                  </div>

                  <div v-else class="symbol-cell">
                    <span>
                      <el-select style="width: 8rem" v-model="currentMeterId" placeholder="选择表计"
                        :disabled="!setParam.usage || loadingMeters" :loading="loadingMeters">
                        <el-option v-for="meter in filterMeterList" :key="meter.id" :label="meter.meter_code"
                          :value="meter.id" />
                      </el-select>
                    </span>
                    <el-button type="primary" link @click="insertMeterSymbol(scope.row.symbol)">
                      插入
                    </el-button>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="explanation" label="解释" align="left" />
              <el-table-column prop="example" label="使用案例" align="left" />
            </el-table>
          </div>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="loading">
          {{ id ? "保存" : "确定" }}
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped>
.custom-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  width: 100%;
}

/* 公式帮助区域样式 */
.formula-help {
  margin-top: 8px;
  width: 100%;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
}

.help-header {
  padding: 8px 12px;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.symbol-table-container {
  padding: 8px;
}

/* 符号单元格样式 */
.symbol-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 8px;
}

.el-button {
  padding: 8px 20px;
  font-size: 14px;
}

.el-button+.el-button {
  margin-left: 12px;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
}
</style>
